package gui;

import game.Game;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;


public class GridPanel extends JPanel implements MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//Reference to the Gui class
	private Gui gui;

	//Reference to the Game class
	private Game game;

	//The images
	private Image blue, red, grid;

	public GridPanel(Gui g)
	{
		this.gui = g;

		//Get the game variabele
		this.game = this.gui.getGame();

		//Load the images
		this.blue = Toolkit.getDefaultToolkit().getImage(getClass().getResource("plaatjes/blue.png"));
		this.red = Toolkit.getDefaultToolkit().getImage(getClass().getResource("plaatjes/red.png"));
		this.grid = Toolkit.getDefaultToolkit().getImage(getClass().getResource("plaatjes/grid-piece.png"));

		this.addMouseListener(this);
	}

	//Draw the tokens
	public void drawTokens(Graphics g)
	{
		byte[][] playingField = this.game.getPlayingField();



		for (int x = 0; x < Game.XSIZE; x++)
		{
			for (int y = Game.YSIZE - 1; y >= 0; y--)
			{
				if (playingField[x][y] == Game.EMPTY)
				{
					break;
				}
				else if (playingField[x][y] == Game.PLAYER1)
				{
					g.drawImage(this.blue, (x * Game.FIELDWIDTH), (y * Game.FIELDWIDTH), this);
				}
				else if (playingField[x][y] == Game.PLAYER2)
				{
					g.drawImage(this.red, (x * Game.FIELDWIDTH), (y * Game.FIELDWIDTH), this);
				}
				else
				{
					//Shouldn't happen.
					System.out.println("The playing field is damaged (error during 'drawTokens').");
				}
			}
		}

	}


	public void paint(Graphics g)
	{
		super.paint(g);

		//Draw the background grid
		for (int x = 0; x < Game.XSIZE; x++)
		{
			for (int y = 0; y < Game.YSIZE; y++)
			{
				g.drawImage(this.grid, x * Game.FIELDWIDTH, y * Game.FIELDWIDTH, this);
			}
		}


		drawTokens(g);
	}

	public void mouseClicked(MouseEvent mouseevent)
	{
		if (game.currentsideIsHuman())
		{
			int column = mouseevent.getX() / Game.FIELDWIDTH;
			
			if (column > Game.XSIZE - 1)
			{
				System.out.println("woot");
				column = Game.XSIZE - 1;
			}
			

			game.playGame(column);
			//game.playGame(column, Game.HUMAN);
		}
	}

	public void mouseEntered(MouseEvent arg0) { }

	public void mouseExited(MouseEvent arg0) { }

	public void mousePressed(MouseEvent arg0) { }

	public void mouseReleased(MouseEvent arg0) { }

}
